package xyz.jcat.sco.admin.oauth2.server.auth;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import xyz.jcat.common.util.CollectionUtils;
import xyz.jcat.sco.common.LoginUser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Getter
@Setter
public class UserDetailsImpl implements UserDetails {

    private LoginUser loginUser;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<Long> roleIds = loginUser.getRoleIds();
        List<GrantedAuthority> authorities;
        if(CollectionUtils.isEmpty(roleIds)) {
            authorities = new ArrayList<>(1);
            authorities.add(new GrantedAuthorityImpl(-1L));
        }else {
            authorities = roleIds.stream().map(roleId -> new GrantedAuthorityImpl(roleId)).collect(Collectors.toList());
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return loginUser.getPassword();
    }

    @Override
    public String getUsername() {
        return loginUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return loginUser.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return loginUser.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return loginUser.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return loginUser.isEnabled();
    }

    public UserDetailsImpl(LoginUser loginUser) {
        this.loginUser = loginUser;
    }
}
